package com.qf.mp2301.postcode.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.qf.mp2301.postcode.entity.Postcode;
import com.qf.mp2301.postcode.service.IPostcodeService;
import com.qf.mp2301.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dong_
 * @since 2023-06-16
 */
@RestController
@RequestMapping("/postcode")
@Slf4j
public class PostcodeController {

    @Autowired
    IPostcodeService postcodeService;

    @Autowired
    RedisTemplate redisTemplate;


    @GetMapping("/consume")
    public R emailConsumer(){

        //1. 获取List中待发送的消息
        String key = "mail:list";

        HashMap map = (HashMap) redisTemplate.opsForList().rightPop(key);

        String to = (String) map.get("to");
        String content = (String) map.get("content");
        log.info("发送给{},内容为{}",to,content);

        // 发邮件
        MailAccount account = new MailAccount();
        account.setHost("smtp.163.com");
        account.setPort(25);
        account.setAuth(true);
        account.setFrom("dong_jl@163.com");
        account.setUser("dong_jl");
        account.setPass("CKGSXROOUIQITGIQ");

        MailUtil.send(account, CollUtil.newArrayList(to), "测试", content, false);

        return R.ok();
    }

    /**
     * 生产者
     * @return
     */
    @GetMapping("/mail")
    public R sendEmail(){
        String content = "hello redis";
        String to = "260107473@qq.com";

        HashMap<String, String> map = new HashMap<>();
        map.put("to",to);
        map.put("content",content);

        // 写入 redis 的一个list中
        String key = "mail:list";
        redisTemplate.opsForList().leftPush(key,map);

        return R.ok(map);
    }

    @GetMapping("/all")
    public R getAllPostCode(){

        String key = "postcode:getAllPostCode";

        List data = redisTemplate.opsForList().range(key, 0, -1);

        if (data!=null&&data.size()>0){
            // 缓存命中 直接返回
            return R.ok(data);
        }else {
            List<Postcode> list = postcodeService.list();

            // 把数据写入 redis中
            redisTemplate.opsForList().rightPushAll(key,list);

            return R.ok(list);
        }

    }


}
